/*
 * Created on 2004/11/23
 * Author aki@akjava.com
 * License Apache2.0 or Common Public License
 */
package com.akjava.wiki.client.core;

import java.util.List;


/**
 * 
 *
 */
public abstract class AbstractConverter implements Converter{

    public NodeConverter[] getNodeConverters() {
        return nodeConverters;
    }
    public void setNodeConverters(NodeConverter[] nodeConverters) {
        this.nodeConverters = nodeConverters;
    }
    private NodeConverter[] nodeConverters;
    
    
    public abstract String getHeader(Document document);
    public abstract String getFooter(Document document);
    protected abstract void startAction(Document document);
    protected abstract void initializeConverters();
    protected List<NodeConverter> list;
    
    
    public String convert(Document document){
        if(list==null){
        	initializeConverters();
        }
        startAction(document);
        String result="";
        result+=getHeader(document);
        for(int i=0;i<document.countNode();i++){
            result+=convert(document.getNodeAt(i),true);
        }
        
        result=finallyAction(result);
        
        result+=getFooter(document);
        return result;
    }

    protected abstract String finallyAction(String text);
    public String convert(Node node,boolean parseChildren){
    /*
     * 
       if(node.getAttributes().length>0)
    System.out.println("last:"+node.getAttributes()[0]);
       */ 
    String result="";
    if(nodeConverters!=null){
        for(int i=0;i<nodeConverters.length;i++){
            if(nodeConverters[i].canConvert(node)){
                result+=nodeConverters[i].toHeader(node);
                break;
            }
        }
    }
    
    if(node instanceof Element && parseChildren){
        Element element=(Element)node;
         for(int i=0;i<element.countNode();i++){
          result+=findParentConverter(element).convertChildren(element.getNodeAt(i),convert(element.getNodeAt(i),true));  
          }
       }
    
    if(nodeConverters!=null){
        for(int i=0;i<nodeConverters.length;i++){
            if(nodeConverters[i].canConvert(node)){
                result+=nodeConverters[i].toFooter(node);
                break;
            }
        }
    }
    
    return result;
    }
    
    public NodeConverter findParentConverter(Node node){
        NodeConverter converter=null;
       
        for(int i=0;i<nodeConverters.length;i++){
            if(nodeConverters[i].canConvert(node)){
                return nodeConverters[i];
               
            }
        }
        return converter;
    }
    
}
